/**系统公共变量**/
var ajaxurl="/svr";			//设置call的访问地址
var userId;					//登录的用户id
var language;				//当前选择的语言版本
var mainSrc;				//mainView加载的src
var windowopen=false;		//判断自定义窗口是否打开
var openProgerssLoad=true;	//判断遮罩是否打开
var sessionManagerId; 		//管理员ID
var sessionManagerName;		//管理员名称
var refererUrl;				//跳转之前mainView引用的src
var async=true;
function call(){
	var service=arguments[0];
	var parameter=arguments[1];
	var success=arguments[2];
	if(arguments.length==4){
		async=arguments[3];
	}
	var heightP=$(window).height()/2-100;
	var widthP=$(window).width()/2-100;
   //coverdiv为遮罩层
	var coverdiv="<div id='bg' style='display: none; position: absolute; top: 0%; left: 0%; width: 100%; height: 100%; background-color: black; z-index:1001; -moz-opacity: 0.7; opacity:.0; filter: alpha(opacity=70);'></div>";
	var show = "<div id='show' style='display: none; position: absolute; top:"+heightP+"px ; left:"+widthP+"px ;z-index:99999; overflow: auto;'><img src=''/></div>";
	var $bg = $.parseHTML(coverdiv);
	var $show = $.parseHTML(show);
	var data = {
        "cmd":service,
        "para": parameter
    };
    
$.ajax({type:'POST',
        url:  getLocationUrl() + ajaxurl + service + ".json",
        data: JSON.stringify(parameter),
        dataType:'json',
        async:async,
		beforeSend:function(xhr){
			if(openProgerssLoad){
                $("body").append($bg).append($show);
                $("#bg").css("display","block");
                $("#show").css("display","block");
			}
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        	if(openProgerssLoad){
				$("#bg").css("display","none");
				$("#show").css("display","none");
        	 }
            if(XMLHttpRequest.status==500){
                //alert('Error' + XMLHttpRequest.responseText);
            	alert('登录超时!');
                window.location.href="login.html";
            }else if (XMLHttpRequest.status==200){
                alert('HttpStatus 200 : Data format incorrect');
            }
         },
        success:function(data){
            if(openProgerssLoad){
                $("#bg").css("display","none");
                $("#show").css("display","none");
            }
            success(data);
        }
      });
}


function callSvr(service,parameter,success){
	var heightP=$(window).height()/2-100;
	var widthP=$(window).width()/2-100;
   //coverdiv为遮罩层
	var coverdiv="<div id='bg' style='display: none; position: absolute; top: 0%; left: 0%; width: 100%; height: 100%; background-color: black; z-index:9998; -moz-opacity: 0.7; opacity:.0; filter: alpha(opacity=70);'></div>";
	var show = "<div id='show' style='display: none; position: absolute; top:"+heightP+"px ; left:"+widthP+"px ;z-index:9999; overflow: auto;'><img src=''/></div>";
	var $bg = $.parseHTML(coverdiv);
	var $show = $.parseHTML(show);
    
$.ajax({type:'POST',
        url:  getLocationUrl()+"/svr/" + service + ".json",
        data: JSON.stringify(parameter),
        dataType:'json',
        async:async,
		beforeSend:function(xhr){
			if(openProgerssLoad){
				$("body").append($bg).append($show);
				$("#bg").css("display","block");
				$("#show").css("display","block");
			}
        }, 
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        	if(openProgerssLoad){
				$("#bg").css("display","none");
				$("#show").css("display","none");
        	 }
            if(XMLHttpRequest.status==500){
                //alert('服务器内部错误.code:500.');
            	alert('登录超时!');
                window.location.href="login.html";
            }else if (XMLHttpRequest.status==200){
                alert('服务器内部错误.code:200.');
            }
         },
        success:function(data){
			if(openProgerssLoad){
				$("#bg").css("display","none");
				$("#show").css("display","none");
        	 }
			if (data.err=="登录超时"){
				alert("登录超时");
				window.location.href="index.html";
				return;
        	}
			if(data.err=="权限不足"){
				alert("权限不足,请联系管理员");
				window.location.href="index.html";
			}
			success(data);
		}
      });
}


//获取层或表单组件的值并转换成json
$.fn.formToJson = function(){
  var valuse = {};
  this.find("*[name]").each(function(index, element) {
	   var elementName = element.name;
	   $(this).find("[getData]").each(function(index, element) {
           if(elementName != undefined && elementName !=""){
			   var result=element.getData.toString();
			   valuse[elementName]==callFunc(result);
		   }
       });
	   if(element.name != undefined && element.name !=""){
			var elementName = element.name;
	        var type = element.type;
			if(element.type == "radio" || type == "checkbox"){
				if(element.checked){
					if(valuse[elementName] == undefined || valuse[elementName] == ''){
				  	    valuse[elementName] = element.value.trim();
				    }else{
						valuse[elementName] = valuse[elementName]+","+element.value.trim();
					  }
				 }else{
					if(valuse[elementName] == undefined || valuse[elementName] == ''){
						valuse[elementName] = ''; 
					}
				 }
			 }else{
			  	  /*
			  	  if(valuse[elementName] == undefined){
				  	  valuse[elementName] = element.value.trim();
				  }else{
					  valuse[elementName] = valuse[elementName]+","+element.value.trim();
				  }
				  */
				 //CMW
				 if (valuse[elementName] == undefined) {
					 if (typeof($(this).attr("isDate"))!="undefined"){
						 if (element.value.trim()==""){
								//valuse[elementName] = "0";
						 }else{
							 valuse[elementName] = element.value.trim();
						 }
					 }else if (typeof($(this).attr("isNum"))!="undefined"){
						 if (element.value.trim()==""){
							 valuse[elementName] = "0";
						 }else{
							 valuse[elementName] = element.value.trim();
						 }
					 }else{
						 valuse[elementName] = element.value.trim();	
					 }
				 } else {
					 valuse[elementName] = valuse[elementName] + "," + element.value.trim();
				 }
			 }
		 }
  });
  return valuse;
};

//jsons为对象里面的所以控件赋值
$.fn.jsonToform = function(json){
	this.find("*[name]").each(function(index, element){
		for(var key in json){
			if(element.name.toLowerCase() == key.toLowerCase()){
				if(element.type == "checkbox"){
					if(json[key] != ''){
					  var checkValue = (json[key]).split(",");
					  for(var str in checkValue){
						  if(element.value == checkValue[str]){
							  element.checked=true ;
						  }
					  }
					}
				}else if(element.type == "radio"){
					if(element.value == json[key]){
						element.checked=true;
					}
				}else if(element.type=="select"){
					if(element.value==json[key]){
						element.checked=true;
					}
				}else{
					element.value = json[key];
				}
				break;
			}
		}
	});
}

$.fn.jsonTotable = function(json) {
	this.find("*[name]").each(function() {
		for ( var key in json) {
			if ($(this).attr("name") == key) {
				$(this).html(json[key]);
				break;
			}
		}
	});
};

//获取访问的项目路径
function getLocationUrl() {
    var protocol = window.location.protocol;//获取当前访问协议
    var host = window.location.host; //获取IP和端口
    //获取项目名称(前面带斜杠)
    var pathName=window.document.location.pathname;
    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    return  protocol+'//'+host+projectName;
}


//去除字符串前后空格
String.prototype.trim=function() {
    return this.replace(/(^\s*)|(\s*$)/g,'');
}

function loadDiv(){
     if($('div[src]').size()==0){
        //调用页面初始化函数
        $("[init]").each(function(){
           // console.log("core.js : call function "+ $(this).attr("init"));
            eval($(this).attr("init"));
            $(this).removeAttr("init");
        });
        //初始化下拉组件
       /* $('select[select-control]').selectpicker();
        $.bootstap_select();
        return;*/
    }
    $('div[src]').each(function(){
        $(this).load($(this).attr('src'),'',function(){
            $(this).removeAttr("src");
            loadDiv();
        });
    });
}

function lang(key){
    if(key==null || key==""){
        return "";
    }
    var fun = "jQuery.i18n.prop(";
    for(var i=0;i<arguments.length;i++) {
        if (typeof (arguments[i]) == "string") {
            fun += "'" + arguments[i] + "',"
        }
    }
    fun = fun.substring(0,fun.lastIndexOf(","));
    fun +=")";
   // console.log("core js lang:"+fun);
    return eval(fun);
}

/**Cookie 相关**/
function getCookie(key){
    var cookieArray=document.cookie.split("; "); //得到分割的cookie名值对
    for (var i=0;i<cookieArray.length;i++){
        var arr=cookieArray[i].split("=");       //将名和值分开
        if(arr[0]==key)return unescape(arr[1]); //如果是指定的cookie，则返回它的值
    }
    return "";
}
function setCookie(key,value){
    document.cookie = key + "="+ value + ";";
}

/**
 * 调用函数，如果是变量需要用{}将其包裹，包含了变量参数时需要在callFunc外包裹eval(callFunc(...))
 * 如果参数都是String 没有包含变量参数则会自动调用。
 * **/
function callFunc(fun){
    if(arguments.length>1){
        var call = true;
        var fun = arguments[0].substring(0,arguments[0].lastIndexOf("(")+1);
        for(var i=1;i<arguments.length;i++){
            if(typeof (arguments[i])=="string"){
                if(arguments[i].indexOf("}")>-1){
                    call = false;
                    fun += arguments[i].substring(arguments[i].indexOf("{")+1,arguments[i].lastIndexOf("}")) + ","
                }else{
                    fun += "'" + arguments[i] + "',"
                }
            }
        }
        fun = fun.substring(0,fun.lastIndexOf(","));
        fun +=")";
    }
    if(call){
    	console.log("core js callFunc :"+fun);
    	eval(fun);
    }else{
        console.log("core js callFunc return:"+fun);
    }
    return fun;
}
/*  
弹出窗口方法
参数说明:position:暂时实现3种 中间(center),左下(left_down),右下(right_down)
popWidth:窗口宽度,popHeight：窗口高度,content:窗口内容,即div内容,windowId:窗口id,parentDivId:父divID;

传入参数：
var windows={
	windowId:"Random",(如果是Random则随机生成ID)
	position:"center",
	popWidth:200,
	popHeight:300,
	title:"这里是标题",
	content:"这里是要显示的内容",
	parentDivId:"parent_DivId",
	src:"",
	}

return windowid;  
*/
function popWindowShow(data){
    windowopen=true; //窗口打开
    var windowId=data.windowId;  //窗口ID
    var popWidth=data.popWidth;  //窗口宽度
    var popHeight=data.popHeight; //窗口高度
    var position=data.position;  //窗口位置
    var content=data.content;
    var zindex=60;
    var title=data.title;
    var src=data.src;
    var nowId;
    var style=data.style;
    //随机情况下，随机生成ID
    if(windowId=="Random"){
        nowId=Math.floor(Math.random()*999+1);
        if(nowId<10){
            windowId="Dialog00"+nowId;
        }else if(nowId<100){
            windowId="Dialog0"+nowId;
        }else{
            windowId="Dialog"+nowId;
        }
        while($("#dialogGroup #"+windowId).length>0){ //如果存在子节点，则重新random
            nowId=Math.floor(Math.random()*999+1);
            if(nowId<10){
                windowId="Dialog00"+nowId;
            }else if(nowId<100){
                windowId="Dialog0"+nowId;
            }else{
                windowId="Dialog"+nowId;
            }
        }
    }else{
        if($("#dialogGroup #"+windowId).length>0){
            alert("该窗口ID已经存在,请重新定义");
        }
    }
    if(content == null||src == undefined || src == ''){
        content="";
    }
    var new_window="<div><div class='panel panel-primary' style='z-index:9990;' id='"+windowId+"'>"+
        "<div id='title'  class='panel-heading'><button id='windowClosed"+windowId+"'"+
        "type='button' class='btn btn-primary btn-sm' style='float:right;position:relative;top:-8px;left:15px;border:0px'>"+
        "<span class='glyphicon glyphicon-remove'></span></button><h4 class='panel-title' style='width:100%'>"+title+"</h3>"+
        "</div><div class='panel-body' id='content"+windowId+"' style='overflow-x:visible;"+style+"'>"+content+"</div></div></div>";
    var wcoverdiv="<div id='wcoverdiv' style='margin:0;padding:0;border:none;width:100%;height:100%;background:#333;opacity:0.6;filter:alpha(opacity=60);z-index:9989;position:fixed;top:0;left:0;'></div>";

    $("#dialogGroup").append(wcoverdiv);
    $("#dialogGroup").append(new_window);
    var windowHeight=$(window).height(); //获取窗口的高度
    var windowWidth=$(window).width();//获取窗口的宽度
    //窗口样式
    var windowcss={"width":""+popWidth+"px","height":""+popHeight+"px","position":"absolute","display":"none"};
    //内容样式
    var contentcss={"height":""+(popHeight-22)+"px","overflow":"auto"};
    //标题样式
    $("#"+windowId).css(windowcss);
    $("#content").css(contentcss);
    if(position=="center"){
        var popY=(windowHeight-popHeight)/2;
        var popX=(windowWidth-popWidth)/2;
    }
    if(position=="left_down"){
        var popY=windowHeight-popHeight-50;
        var popX=50;
    }
    if(position=="right_down"){
        var popY=windowHeight-popHeight-50;
        var popX=windowWidth-popWidth-50;
    }
    $("#"+windowId).css("top",popY-50).css("left",popX).slideDown("fast");
    //内容不存在，src存在
    if(src !== null&&src !== undefined && src !== ''){
        $("#content"+windowId).css({width:"100%",height:""+(popHeight-42)+"px"});
        $("#content"+windowId).load(src);
    }
    closeWindow(windowId);
    return windowId;
}
//关闭窗口的方法(方便动态调用)
function closeWindow(windowId){
    $("#windowClosed"+windowId).click(function(){
        windowopen=false;//窗口关闭
        $("#"+windowId).remove();
        $("#wcoverdiv").remove();
    });
}
$(document).keydown(function(e) {
    e = e || event;
    if (e.keyCode == 27 && windowopen) {
        windowopen = false;// 窗口关闭
        $("#dialogGroup").empty();
    }
});
function menuFix(navBarId,navdata){
	var navBar=$("#"+navBarId);
	for (var i = 0; i < navdata.length; i++) {
		var pid=navdata[i].pid;
		if(pid==null ||pid==""||pid==0){
			navBar.append("<li><a href='#' src="+navdata[i].url+" pid="+navdata[i].menuId+">" + navdata[i].name + "</a></li>");
		}else{
			var pnav=navBar.find("[pid="+pid+"]").parent("li");
			if(pnav.find("ul").length>0){
				pnav.find("ul").append(
						"<li><a href='#' src="+navdata[i].url+" pid="+navdata[i].menuId+">"
						+ navdata[i].name + "</a></li>"
						);
			}else{
				var pul=$("<ul></ul>").appendTo(pnav);
				pul.append(
						"<li><a href='#' src="+navdata[i].url+" pid="+navdata[i].menuId+">"
						+ navdata[i].name + "</a></li>"
						);
			}
		}
		
	}
}
function initOrg(){
	var orgcmd = "orgImpl.getOrgListByPid"
		var para = "";
		call(orgcmd, para, function(result) {
			for (var i = 0; i < result.length; i++) {
				var option = $("[name='orgId']").append(
						"<option value='"+result[i].orgId+"'>" + result[i].name
								+ "</option>");
			}
		});
}